package com.example.demo.controller;

import com.example.demo.common.LoginSession;
import com.example.demo.common.Result;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.example.demo.common.Constant.USER_SESSION_KEY;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 实现注册功能
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/reg")
    public Object reg(String username, String password) {
        //1.进行非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail(-1,"非法请求");
        }
        //2.添加用户
        int res = userService.add(username,password);
        System.out.println(res);
        if(res==1) {
            return Result.success("添加用户成功",1);
        }
        return Result.fail(-1,"添加用户失败");
    }

    /**
     * 实现登陆功能
     * @param request
     * @param username
     * @param password
     * @return
     */

    @RequestMapping("/login")
    public int login(HttpServletRequest request,String username, String password) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return 0;
        }
        UserInfo userinfo = userService.query(username, password);
        if(userinfo==null || userinfo.getId()<=0) {
            return 0;
        }
        //保存到session中-->保存用户登录状态
        HttpSession session = request.getSession();
        session.setAttribute(USER_SESSION_KEY,userinfo);
        return 1;
    }

    /**
     * 实现登出功能
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public Boolean logout(HttpServletRequest request) {
        //获取session
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute(USER_SESSION_KEY)!=null) {
            session.removeAttribute(USER_SESSION_KEY);
            return true;
        }
        return false;
    }

    @RequestMapping("/myinfo")
    public UserInfo myInfo(HttpServletRequest request) {
        UserInfo userinfo = LoginSession.getSessionUserInfo(request);
        if (userinfo != null) {
            return userinfo;
        }
        return null;
    }

}